package com.katze.boot.system.controller;

import com.katze.boot.common.exception.BusinessException;
import com.katze.boot.plugins.shiro.annotations.RestControllerMapping;
import com.katze.boot.plugins.shiro.annotations.RestRequestMapping;
import com.katze.boot.system.domain.Menu;
import com.katze.boot.system.domain.MenuNode;
import com.katze.boot.system.service.MenuService;
import com.katze.common.Message;
import com.katze.common.controller.BaseController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestControllerMapping("/menu")
public class MenuController extends BaseController {

    @Resource
    private MenuService menuService;

    @RestRequestMapping(value = "/{username}")
    public Message getUserRouters(@PathVariable String username) {
        Map<String, Object> routers =  this.menuService.getUserRouters(username);
        return Message.ok().data(routers);
    }

    @RestRequestMapping(permits = "menu:view", skip = true)
    public Message menuList(Menu menu) {
        return Message.ok().data(this.menuService.findMenus(menu));
    }

    @RestRequestMapping(method = RequestMethod.POST, permits = "menu:add", desc = "新增菜单/按钮")
    public Message addMenu(Menu menu) {
        this.menuService.createMenu(menu);
        return Message.ok("新增菜单/按钮成功").data(new MenuNode(menu));
    }

    @RestRequestMapping(method = RequestMethod.DELETE, permits = "menu:delete", desc = "删除菜单/按钮")
    public Message deleteMenus(String... menuIds) {
        this.menuService.deleteMenus(menuIds);
        return Message.ok("删除菜单/按钮成功");
    }

    @RestRequestMapping(method = RequestMethod.PUT, permits = "menu:update", desc = "修改菜单/按钮")
    public Message updateMenu(Menu menu) {
        this.menuService.updateMenu(menu);
        return Message.ok("修改菜单/按钮成功");
    }

    @RestRequestMapping(value = "/export", method = RequestMethod.POST, desc = "导出菜单数据", permits = "menu:export")
    public void export(Menu menu, HttpServletResponse response) throws IOException {
        try {
            List<Menu> menus = this.menuService.findMenuList(menu);
            super.downXlsx("菜单信息表", menus, response);
        } catch (Exception e) {
            throw new BusinessException("导出Excel失败", e);
        }
    }
}